package com.rp.infopub.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rp.common.utils.JsonUtil;
import com.rp.common.utils.RpUtil;
import com.rp.controller.RpController;
import com.rp.infopub.po.Channel;
import com.rp.infopub.service.ChannelService;
import com.rp.system.po.User;

@Controller
@RequestMapping("/rp/infopub/channelMng/")
public class ChannelController extends RpController {

	@Autowired
	private ChannelService channelService;
	
	@RequestMapping("showChannelGrid")
	public ModelAndView showChannelGrid(){
		
		return forward("/rp/infopub/channelMng/channelGrid.jsp");
	}
	
	@ResponseBody
	@RequestMapping("getChannels")
	public List<Channel> getChannels(){
		return channelService.getChannelDao().getAllChannel();
	}
	
	@ResponseBody
	@RequestMapping("saveChannels")
	public String saveChannels(String data){
		try {
			List<Channel> channels = JsonUtil.getMapper().readValue(data, JsonUtil.getCollectionType(ArrayList.class, Channel.class));
			for (Channel channel : channels) {
				if(channel.getId() == null){
					//channel.setName(ESAPI.encoder().encodeForHTML(channel.getName()));
					channel.setCreatorId(User.getCurrentUser().getId());
					channel.setCreatorName(User.getCurrentUser().getRealname());
					channel.setIp(request.getRemoteAddr());
					channel.setCreateDate(RpUtil.getCurrentDatetime());
					channelService.saveChannel(channel);
				}else{
					//channel.setName(ESAPI.encoder().encodeForHTML(channel.getName()));
					channel.setUpdateDate(RpUtil.getCurrentDatetime());
					channelService.updateChannel(channel);
				}
			}
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("deleteChannels")
	public String deleteChannels(String data){
		try {
			List<Channel> channels = JsonUtil.getMapper().readValue(data, JsonUtil.getCollectionType(ArrayList.class, Channel.class));
			for (Channel channel : channels) {
				channelService.deleteChannel(channel.getId());
			}
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
}
